<?php
/**
 * Encrytion based on private key
 * 
 * This class is used to encrypt sensitive data like passwords,
 * credit card info. This data can be decrypted any time if we
 * pass private key used to encrypt. 
 *
 * @category   Core
 * @package    Core_Crypt
 * @copyright  Costrategix Technologies 
 * @author     Sandeep Manne<sandeep.manne@costrategix.com>
 */

class Core_Crypt
{
    public $handler = null;

	public function __construct($key)
	{
        $this->handler = mcrypt_module_open(MCRYPT_BLOWFISH,'',MCRYPT_MODE_ECB,'');
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($this->handler), MCRYPT_RAND);
        $maxKeySize = mcrypt_enc_get_key_size($this->handler);
        mcrypt_generic_init($this->handler, $key, $iv);

	}

	/**
     * Encrypt the given String with the given key
     *
     * @param string $privateKey
     * @param string $data
     * @return string
     */
    public function encrypt($data)
    {
        $length = strlen($data);
        return $length.']%}x{%['.mcrypt_generic($this->handler, $data);
    }

    /**
     * Decrypt the given String with the given key
     *
     * @param string $privateKey
     * @param string $data
     * @return string
     */
    public function decrypt($data)
    {
        $datas = explode("]%}x{%[",$data);
        $data = $datas[1];
        return substr(mdecrypt_generic($this->handler, $data),0,$datas[0]);
    }

    public function __destruct()
    {
        mcrypt_generic_deinit($this->handler);
        mcrypt_module_close($this->handler);
    }
}